package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendSms(String phone) throws Exception {
        Object code =  redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);
        //1.先验证他验证码在不在有效期,在提示不能频繁发送
        if (code != null) {
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //去redis中获取，手机号作为key! 没有： 过期了 或者没有发送过！
        //验证码6位以上（生成一个六位的随机数字）
        int randomNum = (int) (Math.random() * 900000) + 100000;
        //2.正确存到redis设置有效期
        redisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX + phone, randomNum,
                RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
        //3.发送短信
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + randomNum + "\"}\n");
        client.sendSms(smsRequest);
    }

    @Override
    public String login(LoginVo loginVo) {

         Object code = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone());
        //1.判断验证码非空  是否正确
        if (ObjectUtils.isEmpty(code)){
                throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        if (!code.toString().equals(loginVo.getCode())){
            throw  new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        // 2.查询手机号是否存在 不存在插入
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        if (userInfo==null){
            //没有注册
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setAvatarUrl("C:/txw.png");
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("某某"+loginVo.getPhone().substring(loginVo.getPhone().length()-5,loginVo.getPhone().length()));
            userInfoService.save(userInfo);
        }
        //3.检查是否可用
        if (userInfo.getStatus()==BaseStatus.DISABLE){
            throw  new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //4.创建token
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }
}
